//触发的id
var containerIds = PHP['containerIds'];
var fileNum = PHP['fileNum'] ? PHP['fileNum'] : 1;
var mySubmitBtn = $('#mySubmitBtn');
$.each(containerIds, function (i, elem) {
    // 上传文件类型限制
    var extensions = "gif,png,jpeg,jpg";
    if ("undefined" != typeof PHP['extensions'] && "undefined" != typeof PHP['extensions'][i]) {
        extensions = PHP['extensions'][i];
    }
    console.log(extensions)

    // 上传文件路径
    var uploadUrl = PHP['uploadUrl'];
    if ("undefined" != typeof PHP['uploadType'] && "undefined" != typeof PHP['uploadType'][i]) {
        uploadUrl = uploadUrl.replace('__TYPE__', PHP['uploadType'][i])
    }
    console.log(uploadUrl)

    var fileArr = [];
    var fileSizeArr = [];
    var uploader = new plupload.Uploader({
        browse_button: 'select-' + elem,
        // multi_selection: false,
        container: elem,
        flash_swf_url: 'js/Moxie.swf',
        silverlight_xap_url: 'js/Moxie.xap',
        url: uploadUrl,

        filters: {
            mime_types: [ //只允许上传图片和zip文件
                // {title: "Image files", extensions: "gif,png,jpeg,jpg"},
                // {title: "Zip files", extensions: "zip,rar,pdf,doc,xls,xlsx"},
                {title: "files", extensions: extensions}
            ],
            max_file_size: PHP['maxSize'], //最大只能上传500mb的文件
            prevent_duplicates: true //不允许选取重复文件
        },

        init: {
            PostInit: function () {
                $('#post-' + elem).click(function () {
                    uploader.start();
                    return false;
                });
            },

            FilesAdded: function (up, files) {
                plupload.each(files, function (file) {
                    if (up.files.length > fileNum) {
                        layer.msg('最多只能上传' + fileNum + '个文件', {icon: 2});
                        return up.removeFile(file);
                    }

                    $('#' + elem + ' .upload_old_img').remove();
                    document.getElementById('file-' + elem).innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')'
                        + '<p id="' + file.id + '_img" class="upload_img_box"><i class="fa fa-times deleteFile" data-file="' + file.id + '"></i><img src="/static/images/file.png" /></p> <b class="text-danger"></b><div class="my-progress"><div class="my-progress-bar" style="width: 0"></div></div>'
                        + '</div>';

                    // 预览图片
                    !function (file) {
                        previewImage(file, function (imgSrc) {
                            // document.getElementById(file.id + '_img').className = 'upload_img_box';
                            document.getElementById(file.id + '_img').innerHTML = '<i class="fa fa-times deleteFile" data-file="' + file.id + '"></i><img src="' + imgSrc + '" />';
                        })
                    }(file);
                });
            },

            UploadProgress: function (up, file) {
                var d = document.getElementById(file.id);
                d.getElementsByTagName('b')[0].innerHTML = '上传进度：<span>' + file.percent + '%</span>';
                var progressBar = d.getElementsByClassName('my-progress-bar')[0];
                progressBar.style.width = 2 * file.percent + 'px';
                progressBar.setAttribute('aria-valuenow', file.percent);
                mySubmitBtn.attr("disabled", true);
                mySubmitBtn.text('等待上传完再提交...');
            },

            FileUploaded: function (up, file, info) {
                // 修改按钮状态
                mySubmitBtn.attr("disabled", false);
                mySubmitBtn.text('提交');

                var e = JSON.parse(info.response);
                if (e.code > 0) {
                    layer.msg(e.msg, {icon: 2});
                } else {
                    // 添加上传成功的文件
                    fileArr.push(e.data.urlRoot);
                    fileSizeArr.push(e.data.size);
                    $('#' + elem + '-input').val(fileArr);
                    $('#' + elem + '-size-input').val(fileSizeArr);
                    layer.msg('文件上传成功', {icon: 1});
                }
            },

            Error: function (up, err) {
                if (err.code == -600) {
                    layer.msg('文件大小超过限制', {icon: 2});
                } else if (err.code == -601) {
                    layer.msg('上传文件类型不允许', {icon: 2});
                } else if (err.code == -602) {
                    layer.msg('这个文件已经上传过一遍了', {icon: 2});
                } else {
                    layer.msg(document.createTextNode("\nError xml:" + err.response), {icon: 2});
                }
            }
        }
    });

    uploader.init();

    // 删除文件
    $('#' + elem).on('click', '.deleteFile', function () {
        var fileId = $(this).data('file');
        // uploader移除文件
        uploader.removeFile(fileId);
        // 删除容器
        $('#' + fileId).remove();
    });
});

/**
 * 预览图片
 * plupload中为我们提供了mOxie对象
 * 有关mOxie的介绍和说明请看：https://github.com/moxiecode/moxie/wiki/API
 * @param file plupload事件监听函数参数中的file对象
 * @param callback 为预览图片准备完成的回调函数
 */
function previewImage(file, callback) {
    // 确保文件是图片
    if (!file || !/image\//.test(file.type)) return;
    // gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
    if (file.type == 'image/gif') {
        var fr = new moxie.file.FileReader();
        fr.onload = function () {
            callback(fr.result);
            fr.destroy();
            fr = null;
        };
        fr.readAsDataURL(file.getSource());
    } else {
        var preloader = new moxie.image.Image();
        preloader.onload = function () {
            // preloader.downsize(300, 300);//先压缩一下要预览的图片,宽300，高300
            var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
            // callback传入的参数为预览图片的url
            callback && callback(imgsrc);
            preloader.destroy();
            preloader = null;
        };
        preloader.load(file.getSource());
    }
}

